<script setup>
  import { reactive, ref, watch } from 'vue'
  import { createShareService } from '@/api/share.js'
  import { shortName } from '@/utils/common.js'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      required: true
    },
    files: {
      type: Array,
      default: () => []
    }
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  const shareConfigRef = ref(null)

  // 分享配置
  const shareConfig = ref({
    shareDayType: 1, // 默认7天
    shareType: 0, // 默认系统生成
    customCode: '', // 自定义提取码
    shareName: '' // 分享名称
  })

  // 分享链接信息
  const shareInfo = ref({
    shareUrl: '',
    shareCode: '',
    period: ''
  })

  const rules = reactive({
    shareDayType: [
      {
        required: true,
        trigger: 'change'
      }
    ],
    shareType: [
      {
        required: true,
        trigger: 'change'
      }
    ],
    customCode: [
      { required: true, message: '提取码不能为空', trigger: 'blur' },
      { min: 4, max: 4, message: '提取码为4位', trigger: 'blur' }
    ]
  })

  // 显示分享结果对话框
  const showShareRes = ref(false)

  // 是否正在创建分享链接
  const isLoading = ref(false)

  // 格式化分享名称
  const setShareName = files => {
    if (files.length > 1) {
      let str = ''
      for (let i = 0; i < files.length; i++) {
        str += files[i].filename
      }

      let filename = files[0].filename
      if (str.length > 14) {
        filename = filename.substring(0, 20 / 2)
      }

      const res = filename + '...' + `等${files.length}个文件`
      shareConfig.value.shareName = res
      return res
    } else {
      let filename = files[0]?.filename
      if (filename) {
        shareConfig.value.shareName = shortName(filename)
        return shortName(filename)
      }
    }
  }

  // 监听对话框可见性变化
  watch(
    () => props.modelValue,
    newVal => {
      if (!newVal) {
        // 延迟重置状态，等待对话框动画完成
        setTimeout(() => {
          shareConfig.value.shareName = ''
          shareConfig.value.shareDayType = 1
          shareConfig.value.shareType = 0
          shareConfig.value.customCode = ''
          shareInfo.value = { shareUrl: '', shareCode: '' }
          showShareRes.value = false
        }, 300)
      }
    }
  )

  // 创建分享链接
  const createShareLink = async () => {
    shareConfigRef.value.validate(async isValid => {
      if (isValid) {
        try {
          isLoading.value = true
          const params = {
            shareName: shareConfig.value.shareName,
            shareFileIds: props.files.map(file => file.fileId),
            shareDayType: shareConfig.value.shareDayType,
            shareType: shareConfig.value.shareType,
            customCode: shareConfig.value.shareType === 'custom' ? shareConfig.value.customCode : ''
          }

          // 调用分享接口
          const res = await createShareService(
            params.shareName,
            params.shareType,
            params.shareDayType,
            params.shareFileIds
          )

          // 保存分享结果
          shareInfo.value = {
            shareUrl: res.data.shareUrl,
            shareCode: res.data.shareCode,
            period: res.data.period
          }

          showShareRes.value = true
          emit('success')
        } catch (error) {
          console.error(error)
        } finally {
          isLoading.value = false
        }
      }
    })
  }

  // 关闭对话框
  const closeDialog = () => {
    emit('update:modelValue', false)
  }
</script>

<template>
  <el-dialog
    :close-on-click-modal="false"
    :model-value="modelValue"
    :show-close="true"
    title="分享"
    width="650px"
    @close="closeDialog"
    @update:model-value="val => emit('update:modelValue', val)"
  >
    <div v-if="!showShareRes" style="padding: 0 30px">
      <el-alert
        :closable="false"
        :title="setShareName(files)"
        show-icon
        style="margin-bottom: 20px; height: 35px"
        type="info"
      >
      </el-alert>

      <el-form
        ref="shareConfigRef"
        :model="shareConfig"
        :rules="rules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="有效期" prop="shareDayType">
          <el-radio-group v-model="shareConfig.shareDayType">
            <el-radio :value="3">1天</el-radio>
            <el-radio :value="1">7天</el-radio>
            <el-radio :value="2">30天</el-radio>
            <el-radio :value="0">永久分享</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="提取码" prop="shareType">
          <el-radio-group v-model="shareConfig.shareType">
            <el-radio :value="1" disabled>自定义</el-radio>
            <el-radio :value="0">系统生成</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="shareConfig.shareType === 1" prop="customCode">
          <el-input
            v-model="shareConfig.customCode"
            maxlength="4"
            placeholder="请输入4位提取码"
            prop="customCode"
            show-word-limit
            style="width: 180px"
          />
        </el-form-item>
      </el-form>
    </div>

    <div
      v-else
      style="padding: 0 30px; display: flex; flex-direction: column; align-items: flex-start"
    >
      <el-alert
        :closable="false"
        show-icon
        style="margin-bottom: 20px; height: 35px"
        title="成功创建私密链接"
        type="success"
      >
      </el-alert>

      <div
        style="
          width: 474px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 20px;
        "
      >
        <span>分享链接</span>
        <el-input v-model="shareInfo.shareUrl" readonly style="width: 400px">
          <template #append>{{ shareInfo.period }}</template>
        </el-input>
      </div>

      <div
        style="
          width: 174px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 30px;
        "
      >
        <span>提取码</span>
        <el-input v-model="shareInfo.shareCode" readonly style="width: 100px" />
      </div>

      <el-text size="small" type="info"
        >严厉打击色情低俗等不良信息的传播行为，如发现将封禁账号。
      </el-text>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="!showShareRes" @click="closeDialog">取消</el-button>
        <el-button
          v-if="!showShareRes"
          type="primary"
          :loading="isLoading"
          @click="createShareLink"
        >
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped>
  ::v-deep .el-input-group__append {
    width: 75px;
    background: #ffffff;
  }
</style>
